package com.wang.service;

import com.wang.doc.CourseDoc;
import com.wang.hrm.query.CourseQuery;
import com.wang.hrm.util.PageList;
import com.wang.repository.CourseElasticsearchRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ESService {

    @Autowired
    private CourseElasticsearchRepository courseElasticsearchRepository ;

    public PageList<CourseDoc> searchCourse(CourseQuery courseQuery) {
        //1.把courseQuery封装成  NativeSearchQueryBuilder
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        //查询条件=====================================================================================
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //DSL查询，must：必须匹配的条件
        List<QueryBuilder> must = boolQueryBuilder.must();
        if(StringUtils.hasLength(courseQuery.getKeyword())){
            //        keyword: "" ：must   -> match
            must.add(QueryBuilders.matchQuery("name",courseQuery.getKeyword()));
        }
        //DSL过滤
        List<QueryBuilder> filter = boolQueryBuilder.filter();
        if(null != courseQuery.getProductType()){
            //        productType: "1040"   ->  term
            filter.add(QueryBuilders.termQuery("courseTypeId",courseQuery.getProductType()));
        }
        if(null != courseQuery.getPriceMin()){
            //        priceMin: null    ->  range
            filter.add(QueryBuilders.rangeQuery("price").gte(courseQuery.getPriceMin()));
        }
        if(null != courseQuery.getPriceMax()){
            //        priceMax: null    ->  range
            filter.add(QueryBuilders.rangeQuery("price").lte(courseQuery.getPriceMax()));
        }

        //关联查询条件
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        //排序条件=====================================================================================
        if(StringUtils.hasLength(courseQuery.getSortField())){
            //排序的列
            String sortFieldName = "price";
            //sortField: "xl" -> saleCount
            switch (courseQuery.getSortField().toUpperCase()){
                case "XL": sortFieldName = "saleCount";break;
                case "XP": sortFieldName = "onlineTime";break;
                case "PL": sortFieldName = "commentCount";break;
                case "JG": sortFieldName = "price";break;
                case "RQ": sortFieldName = "viewCount";break;
            }
            //排序的方式
            SortOrder sortOrder = SortOrder.DESC ;
            if(StringUtils.hasLength(courseQuery.getSortType()) && courseQuery.getSortType().toUpperCase().equals("ASC")){
                sortOrder = sortOrder.ASC;
            }
            //添加排序条件
            nativeSearchQueryBuilder.withSort(new FieldSortBuilder(sortFieldName).order(sortOrder));
        }
        //分页条件=====================================================================================
        nativeSearchQueryBuilder.withPageable(PageRequest.of(courseQuery.getPage() - 1,courseQuery.getRows()));

        //执行查询处理结果========================================================================================================

        //2.执行查询获取结果
        SearchQuery searchQuery = nativeSearchQueryBuilder.build();

        Page<CourseDoc> page = courseElasticsearchRepository.search(searchQuery);

        //3.要把ES的结果page对象转成PageList对象返回
        return new PageList<CourseDoc>(page.getTotalElements(),page.getContent());
    }
}
